package com.funquer.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-3-20
 * Time: 上午10:49
 * To change this template use File | Settings | File Templates.
 */
public class FreemarkerUtil {

    private static FreemarkerUtil freemarkerUtil=null;

    private FreemarkerUtil(){}

    public static FreemarkerUtil getInstance(){
        if(freemarkerUtil==null){
            freemarkerUtil=new FreemarkerUtil();
        }
        return freemarkerUtil;
    }

    private Template getTemplate(String name){
        Configuration configuration=new Configuration();
        configuration.setClassForTemplateLoading(this.getClass(),"/ftl");
        try {
            Template template= configuration.getTemplate(name);
            template.setEncoding("UTF-8");
            return template;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public void print(String name,Map<String,Object> root){
        Template template=this.getTemplate(name);
        try {
            template.process(root,new PrintWriter(System.out));
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void fPrint(String name,Map<String,Object> root,String outFile){
        FileWriter writer=null;
        try {
            File file = new File(outFile);
            if(!file.exists()){
                file.getParentFile().mkdirs();
            }
            writer=new FileWriter(outFile);
            Template template=this.getTemplate(name);
            try {
                template.process(root,new PrintWriter(writer));
            } catch (TemplateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(writer!=null){
                    writer.close();
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }


}
